import { createRouter, createWebHistory } from 'vue-router'
import AuthUtils from '@/utils/auth.js'

// Layout
import Layout from '@/layout/Layout.vue'

// 公共路由
export const constantRoutes = [
  // 登录路由
  {
    path: '/login',
    component: () => import('@/views/Login.vue'),
    name: 'Login',
    meta: { title: '登录', hidden: true },
    hidden: true
  },
  // 需要认证的路由
  {
    path: '',
    component: () => import('@/layout/Layout.vue'),
    hidden: false,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        component: () => import('@/views/index.vue'),
        name: 'Index',
        meta: { title: '一体化页面', icon: 'component', requiresAuth: true }
      },
      {
        path: '/account-summary',
        component: () => import('@/views/AccountSummary.vue'),
        name: 'AccountSummary',
        meta: { title: '账户汇总管理', icon: 'component', requiresAuth: true }
      },
      {
        path: '/stock-trading-list',
        component: () => import('@/views/StockTradingList.vue'),
        name: 'StockTradingDetail',
        meta: { title: '股票交易详情', icon: 'component', requiresAuth: true }
      },
      {
        path: '/stock-statistics',
        component: () => import('@/views/StockStatistics.vue'),
        name: 'StockStatistics',
        meta: { title: '股票统计数据', icon: 'component', requiresAuth: true }
      },
      {
        path: '/data-sync',
        component: () => import('@/views/DataSync.vue'),
        name: 'DataSync',
        meta: { title: '数据同步管理', icon: 'component', requiresAuth: true }
      },
      {
        path: '/stock-price-chart',
        component: () => import('@/views/StockPriceDashboard.vue'),
        name: 'StockPriceChart',
        meta: { title: '股票价格曲线', icon: 'trending-up', requiresAuth: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes,
  scrollBehavior: () => ({ y: 0 })
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  
  if (requiresAuth) {
    // 需要认证的路由
    if (AuthUtils.isLoggedIn()) {
      // 已登录，刷新登录状态
      AuthUtils.refreshLogin()
      next()
    } else {
      // 未登录，重定向到登录页面
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    // 不需要认证的路由（如登录页面）
    if (to.path === '/login' && AuthUtils.isLoggedIn()) {
      // 已登录用户访问登录页面，重定向到首页
      next('/')
    } else {
      next()
    }
  }
})

// 路由后置守卫
router.afterEach((to) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 样式测试系统` : '样式测试系统'
})

export default router